package com.servlet;

import com.dao.impl.MessageDaoimpl;
import com.entity.Message;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author 羡羡
 */
@WebServlet("/MessageServlet/*")
public class MessageServlet extends  BaseServlet{
    MessageDaoimpl meimp=new MessageDaoimpl();
    /**
     * 查询所有
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void searchmessage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        List list=meimp.search();
        request.setAttribute("lylist",list);
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }

    /**
     * 发布评论
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     * @throws SQLException
     */
    protected void addmessage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        String uname = (String)request.getSession().getAttribute("uname");
        String img = (String)request.getSession().getAttribute("img");
        String comment=request.getParameter("comment");
        SimpleDateFormat simp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = simp.format(new Date());
        Message m = new Message(uname,comment,img,date);
        int de=meimp.addMessage(m);
        if(de<0){
            response.getWriter().write("<script>alert('发布失败！');location.href='index.jsp'</script>");
        }
        request.getRequestDispatcher("MessageServlet/searchmessage").forward(request, response);
    }

    /**
     * 删除留言
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     * @throws SQLException
     */
    protected void delemessage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        String id=request.getParameter("id");
        int lid=Integer.parseInt(id);
        int de=meimp.deleteMessage(lid);
        if(de<0){
            response.getWriter().write("<script>alert('删除失败！');location.href='index.jsp'</script>");
        }
        request.getRequestDispatcher("MessageServlet/searchmessage").forward(request, response);
    }
}
